<?php
apf_require_class('APF_Controller');
apf_require_class('Portal_Urls');
apf_require_class('Flow_Urls');
apf_require_class("Bll_Hr_OutInterface");
apf_require_class("Const_Tip");
apf_require_class("Bll_Flow_Role");
apf_require_class("Bll_Flow_OperateLog");
apf_require_class("Const_Flow");
apf_require_class('Bll_Flow_ApplyRelation');
apf_require_class("Bll_Flow_Info");
apf_require_class("Util_Tools");

abstract class AbstractController extends APF_Controller {

    /**
     * @var APF
     */
    protected $apf = NULL;

    /**
     * @var NHRequest
     */
    protected $request = NULL;

    /**
     * @var APF_Response
     */
    protected $response = NULL;

    /**
     * @ 流程列表
     */
    protected $flow_list = NULL;

    //用户信息
    protected $user_info;

    public function __construct() {
        parent::__construct();
        $this->apf = APF::get_instance();
        $this->request = $this->apf->get_request();
        $this->response = $this->apf->get_response();

        $this->update_session();
        $this->is_logout();
        setcookie("anjuke-portal", $_COOKIE['anjuke-portal'], time() + 86400);
    }

    private function  update_session(){
        $this->session_act();
        if(isset($_SESSION['user_id']) && $_SESSION['user_id'] !=''){
            //suid 伪装登陆
            $params = $this->request->get_parameters();
            $ip = $this->request->get_client_ip();
            if(substr($ip, 0,7) == '192.168' || $ip == '127.0.0.1'){
                if(isset($params['suid'])){
                    unset($_SESSION['system_sa']);
                    unset($_SESSION['user_security_enable']);
                    $this->set_user_info($params['suid']);
                }
            }
            if($ip=='221.133.228.74' || $ip=='10.10.6.3'){
                if(isset($params['tzw_suid'])){
                    $this->set_user_info($params['tzw_suid']);
                }
            }
            if($_SERVER['REQUEST_URI'] =='/login/' || $_SERVER['REQUEST_URI'] =='/login'){
                $url = "http://".$_SERVER['HTTP_HOST'].'/';
                $this->response->redirect($url,false,false);
            }
            $userinfo = $this->set_user_info($_SESSION['user_id']);
            $this->request->set_attribute('userinfo',$this->user_info);
        }else{
            //未登录跳转到登录页面
            if(!preg_match('/\/login\//',$_SERVER['REQUEST_URI'])){
                $lasturl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                $keep = '';
                if($lasturl) {
                    $keep = '?back='.base64_encode($lasturl);
                }
                $url = "http://".$_SERVER['HTTP_HOST'].'/login/'.$keep;
                $this->response->redirect($url,false,false);
            }
        }
    }
        public function session_act(){
            //TODO 其他操作
            session_name('anjuke-portal');
            //session_cache_expire(86400);
            session_start();

        }

        public function get_user_info(){
            return $_SESSION;
        }

        public function get_user_id(){
            return $_SESSION['user_id'];
        }

        /**
         * 根据流程类型，阶段，获得该阶段下能操作的角色和对应的操作ID
         * @param int $flow_type 流程类型
         * @param int $step_id 阶段ID
         * @return array
         */
        protected function _get_flow_step($flow_type, $step_id = 0, $opt_id = 0){
            $retrun = array();
            if(empty($flow_type)){
                return $retrun;
            }
            $return = array();
            $this->flow_list = Const_Flow::flow_to_opt();
            $retrun = $this->flow_list[$flow_type];
            if($step_id){
                $retrun = $retrun[$step_id];
            }
            if($opt_id){
                $retrun = array_keys($retrun, $opt_id);
                if($retrun){
                    $retrun = array_pop($retrun);
                }
            }
            return $retrun;
        }
        /**
         * 检测该flow_id的申请人是否是自己
         * @param unknown_type $flow_id
         * @return boolean
         */
        protected function _check_applyer($flow_id){
            $bll_log = new Bll_Flow_OperateLog();
            //如果申请人是自己则可以查看
            $log_info = $bll_log->get_flow_log($flow_id,1);
            if($log_info && ($log_info[0]['opt_user_id'] == $this->user_info['user_id'])){
                return true;
            }else{
                return false;
            }
        }
        /**
         * 检测是否有查看该流程权限
         * @param int $city_id 被办理人城市ID
         * @param int $flow_type 四大流程类型ID
         * @param int $step_id 需要验证的阶段
         * @param int $flow_id *如果需要检测的操作为“主管确认”等，需要传这个参数*
         */
        protected function _check_read_flow_auth($city_id, $flow_type, $step_id,$flow_id){
            //检测申请人是不是该用户
            /*if($this->_check_applyer($flow_id)){
                return true;
            }*/

            //查询操作过的人
            $bll_log = new Bll_Flow_OperateLog();
            $log_list = $bll_log->get_flow_log($flow_id);
            if($log_list){
                foreach($log_list as $row){
                    if($this->user_info['user_id'] == $row['opt_user_id']){
                        return true;
                    }
                }
            }
            //查询有修改权限的人
            if($this->_check_auth($city_id, $flow_type, $step_id,$flow_id)){
                return true;
            }
            //是否是该城市的HR
            if(in_array($city_id, $this->user_info['role_list'][Const_Flow::ROLE_HR])){
                return true;
            }
            $bll_flow = new Bll_Flow_Info();
            $flow_info = $bll_flow->find_by_id($flow_id);
            if(!empty($this->user_info['role_list'][Const_Flow::ROLE_RECRUIT]) && $flow_info['flow_type']==Const_Flow::FLOW_TYPE_RECRUIT){
                $role_recruit_city = $this->user_info['role_list'][Const_Flow::ROLE_RECRUIT];
                if(in_array($city_id, $role_recruit_city) || in_array(11, $role_recruit_city)){
                    return true;
                }
            }
            return false;
        }

        /**
         * 验证用户权限
         * @param int $city_id 被办理人城市ID
         * @param int $flow_type 四大流程类型ID
         * @param int $step_id 需要验证的阶段
         * @param int $flow_id *如果需要检测的操作为“主管确认”等，需要传这个参数*
         * @param int $old_city_id 纯浪费的参数TODO
         * @return boolean
         */
        protected function _check_auth($city_id, $flow_type, $step_id, $flow_id=0,$old_city_id=0){
            $return = array();
            if(!$this->user_info['role_list'] || empty($city_id) || empty($flow_type) || empty($step_id)){
                return $return;
            }
            //检测下一步是否有人操作过，如果操作做过就不能再更改
            if($flow_id){
                $bll_log = new Bll_Flow_OperateLog();
                $log_info = $bll_log->get_flow_log($flow_id,$step_id+1);
                if($log_info){
                    $step_id++;
                }
            }
            ///循环查询该阶段，所有操作，该用户
            $opt_list = $this->_get_flow_step(intval($flow_type), intval($step_id));
            if(!$opt_list){
                return $return;
            }
            foreach( $opt_list as $role_type => $opt_id){
                //如果是离职的交接资料操作
                if(Const_Flow::PHASE_31 == $opt_id){
                    if($flow_id){
                        $bll_flow = new Bll_Flow_Info();
                        $flow_info = $bll_flow->find_by_id($flow_id);
                        if($flow_info['user_id'] == $this->user_info['user_id']){
                            $return[] = $opt_id;
                        }
                    }
                }else{
                    //该角色类型是否存在
                    $has_role = isset($this->user_info['role_list'][$role_type]);
                    if($has_role){
                        //如果是主管则检测
                        if($role_type == Const_Flow::ROLE_SUPERIOR){
                            //如果需要检测主管，则不检测城市
                            if($flow_id){
                                if($this->_check_parent_auth($flow_id,$step_id)){
                                    $return[] = $opt_id;
                                }
                            }else{
                                $return[] = $opt_id;
                            }
                        }else{//检测该角色类型所在城市
                            if($flow_type==Const_Flow::FLOW_TYPE_TRANSFER && $role_type==Const_Flow::ROLE_IT){
                                $city_id = $old_city_id ? $old_city_id : $city_id;
                            }
                            if(in_array($city_id, $this->user_info['role_list'][$role_type])){
                                $return[] = $opt_id;
                            }
                        }
                    }
                }
            }
            return $return;
        }

        /**
         * 验证是否该轮到该主管操作该流程
         * @param unknown_type $parent_id
         * @param unknown_type $flow_id
         * @return boolean
         */
        protected function _check_parent_auth($flow_id,$flow_stage){
            $return = false;
            if(!isset($flow_id)){
                return $return;
            }
            //检查是否有主管角色
            if(!$this->_check_superior()){
                return $return;
            }
            $bll_rela = new Bll_Flow_ApplyRelation();
            $re = $bll_rela->get_relation($flow_id,array('user_id'=>$this->user_info['user_id'],'flow_stage'=>$flow_stage));
            if(!$re){
                return false;
            }
            return true;
        }
        /**
         * 构造用户登陆数据
         */
        public function set_user_info($uid){
            $this->session_act();
            $bll = new Bll_Hr_OutInterface();
            $this->user_info = $bll->get_user_base_info($uid);
            $this->user_info['is_allow_transfer']=0;
            if($this->user_info['p_level'] > 6 || $this->user_info['m_level'] > 3){
                $this->user_info['is_allow_transfer']=1;
            }
            $_SESSION = $this->user_info;
            $_SESSION['code'] = $this->user_info['user_code'];
            //获得用户角色
            $this->user_info['role_list'] = $this->_get_role_list($this->user_info['user_id']);
        }
        /**
         * 获得角色列表
         * @param unknown_type $user_id
         * @return multitype:
         */
        private function _get_role_list($user_id){
            $return = array();
            $bll_role = new Bll_Flow_Role();
            $role_list = $bll_role->get_role_by_user_id($user_id);
            if(!$role_list){
                $return = array();
            }

            foreach($role_list as $row){
                $return[$row['role_type']][] = $row['city_id'];
            }
            //如果是apply_relation有表有数据主管权限
            if($this->_check_superior()){
                $return[Const_Flow::ROLE_SUPERIOR][] = $this->user_info['work_city_id'];
            }
            //添加普通员工权限
            $return[Const_Flow::ROLE_STAFF][] = $this->user_info['work_city_id'];
            //添加seo权限
            $ceo_uid = $this->apf->get_config('ceo_uid');
            if($user_id == $ceo_uid){
                $return[Const_Flow::ROLE_CEO][] = $this->user_info['work_city_id'];
            }
            return $return;
        }
        /**
         * 检测是否主管
         */
        protected function _check_superior(){
            $bll_rela = new Bll_Flow_ApplyRelation();
            $re = $bll_rela->is_super_count($this->user_info['user_id']);
            if($re){
                return true;
            }
            return false;
        }
        /**
         * 退出登录
         */
        public function is_logout(){
            //TODO 销毁用户信息 跳转到登录页面
            if(isset($_GET['logout'])){
                $this->session_act();
                session_unset();
                session_destroy();
                $apf = APF::get_instance();
                $oauth = APF::get_instance()->get_config('oauth_info');
                if($oauth){
                    $logout = $oauth['oauth_url'].'/logout.php?client_id='.$oauth['client_id'].'&client_secret='.$oauth['client_secret'];
                    $apf->get_response()->redirect($logout,false,false);
                }else{
                    $apf->get_response()->redirect('/login/',false,false);
                }
            }
        }
        /**
         *
         * @param int $status 0错误 1成功
         * @param unknown_type $res
         */
        public function json_encode($status,$res){
            $result = array(
                    'errcode'=>$status
            );
            if($status){
                $result['data']=$res;
            }else{
                $result['msg']=$res;
            }
            echo json_encode($result);
            exit();
        }
        /**
         * 跳转到提示页面
         * @param int $status 状态，1：正确状态，0：错误状态
         * @param str $code 错误码，统一到tip.php内定义
         * @param str $next 跳转到哪个链接
         */
        protected function show_tips($code = 'ERROR_SYSTEM', $next='', $status = 0){
            $next = !empty($next)
            ? $next
            : ((!empty($_SERVER['HTTP_REFERER']) && !strpos($_SERVER['HTTP_REFERER'], 'ShowTips')) ? $_SERVER['HTTP_REFERER'] : Flow_Urls::base_url());

            $params = "?status=$status&code=$code";

            if($next){
                $params .= '&next='.base64_encode($next);
            }
            $url = Flow_Urls::build_jump_url($params);
            $this->response->redirect($url);
        }

        /**
         * 检测是否有管理角色权限
         * 方便内网不用配权限
         * @return boolean
         */
        protected function check_role_auth(){
            $return = false;
            $role_admin = $this->apf->get_config('role_admin');
            if(in_array($this->user_info['user_code'], $role_admin)){
                $return = true;
            }
            return $return;
        }

        /**
         * 前台操作提示
         * @param string $url 提示后跳转到
         * @param string $msg 提示信息
         */
        public function alert($url,$msg){
            $base_path = $this->apf->get_config('base_domain');
            $url = "http://".$base_path.$url;
            if($url && $msg){
                header("Content-type: text/html; charset=utf-8");
                echo '<script>alert('.$msg.');window.location.href="'.$url.'";</script>';
                exit(0);
            }
        }
}
